package com.ruoyi.web.controller.finance;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.finance.domain.*;
import com.ruoyi.finance.domain.DTO.KltPurchaseDetailDTO;
import com.ruoyi.finance.domain.DTO.KltSalesDetailStockDTO;
import com.ruoyi.finance.domain.VO.CheckOutVO;
import com.ruoyi.finance.service.KltPurchaseDetailService;
import com.ruoyi.finance.service.KltSalesDetailService;
import com.ruoyi.finance.service.KltSalesOrderService;
import com.ruoyi.finance.service.KltStockService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import static com.ruoyi.common.core.domain.AjaxResult.success;

/**
 * (KltSalesDetail)表控制层
 *
 * @author makejava
 * @since 2024-12-19 12:18:03
 */
@RestController
@RequestMapping("finance/kltSalesDetail")
public class KltSalesDetailController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private KltSalesDetailService kltSalesDetailService;

    @Resource
    private KltSalesOrderService kltSalesOrderService;

    @Resource
    private KltStockService kltStockService;


    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @param kltSalesDetail 查询实体
     * @return 所有数据
     */
    @GetMapping("list")
    public TableDataInfo selectAll(Page<KltSalesDetail> page, KltSalesDetail kltSalesDetail) {
        startPage();
        List<KltSalesDetailStockDTO> page1 = kltSalesDetailService.getAllKltPurchaseDetailStockList(kltSalesDetail);

        return getDataTable(page1);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public AjaxResult selectOne(@PathVariable Serializable id) {
        return success(this.kltSalesDetailService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param kltSalesDetail 实体对象
     * @return 新增结果
     */
    @PostMapping
    public AjaxResult insert(@RequestBody KltSalesDetail kltSalesDetail) {
        return success(this.kltSalesDetailService.save(kltSalesDetail));
    }

    /**
     * 修改数据
     *
     * @param kltSalesDetail 实体对象
     * @return 修改结果
     */
    @PutMapping
    public AjaxResult update(@RequestBody KltSalesDetail kltSalesDetail) {
        return success(this.kltSalesDetailService.updateById(kltSalesDetail));
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping
    public AjaxResult delete(@RequestParam("idList") List<Long> idList) {
        return success(this.kltSalesDetailService.removeByIds(idList));
    }



    @Transactional
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<KltSalesDetailStockDTO> util = new ExcelUtil<KltSalesDetailStockDTO>(KltSalesDetailStockDTO.class);
        List<KltSalesDetailStockDTO> KltPurchaseDetailDTO = util.importExcel(file.getInputStream());
        String operName = getUsername();

        List<KltSalesDetail> kltSalesDetailStockDTOS = new ArrayList<>();
        for (KltSalesDetailStockDTO KltSalesDetailStockDTO : KltPurchaseDetailDTO) {
//        找到批次id 或新增
            KltSalesOrder kltSalesOrder = new KltSalesOrder();
            KltStock kltStock = new KltStock();
            KltSalesDetail kltSalesDetail = new KltSalesDetail();


            kltSalesOrder.setSalesOrderNumber(KltSalesDetailStockDTO.getSalesOrderNumber());
            kltSalesOrder.setSalesDeliveryDate(KltSalesDetailStockDTO.getSalesDeliveryDate());
            kltSalesOrder.setSalesDate(KltSalesDetailStockDTO.getSalesDate());
            kltSalesOrder.setCustomerName(KltSalesDetailStockDTO.getCustomerName());
            kltSalesOrder.setSalesInvoiceNumber(KltSalesDetailStockDTO.getSalesInvoiceNumber());
            kltSalesOrder.setSalesInvoiceDate(KltSalesDetailStockDTO.getSalesInvoiceDate());
            kltSalesOrder.setSalesInvoiceQuantity(KltSalesDetailStockDTO.getSalesInvoiceQuantity());
            kltSalesOrder.setSalesInvoiceAmount(KltSalesDetailStockDTO.getSalesInvoiceAmount());
            kltSalesOrder.setUnpaidSalesInvoiceAmount(KltSalesDetailStockDTO.getUnpaidSalesInvoiceAmount());
            kltSalesOrder.setSalesCost(KltSalesDetailStockDTO.getSalesCost());
            kltSalesOrder.setRemarks(KltSalesDetailStockDTO.getRemarks());

            Page<KltSalesOrder> page = new Page<KltSalesOrder>(1,10000);
            Page<KltSalesOrder> count = kltSalesOrderService.page(page, new QueryWrapper<>(kltSalesOrder));
            if(count.getRecords().isEmpty()){
                kltSalesOrder.setSalesOrderId(kltSalesOrderService.getMaxId()+1);
                kltSalesOrder.setCreateSource(operName);
                kltSalesOrder.setUpdateUser(operName);
                try {
                    boolean save = kltSalesOrderService.save(kltSalesOrder);
                } catch (Exception e) {
                    throw new RuntimeException("添加批次失败");
                }
            }else {
                kltSalesOrder.setSalesOrderId(count.getRecords().get(0).getSalesOrderId());
            }



            kltStock.setProductName(KltSalesDetailStockDTO.getProductName());
            kltStock.setModel(KltSalesDetailStockDTO.getModel());
            kltStock.setUnit(KltSalesDetailStockDTO.getUnit());

            Page<KltStock> KltStockPage = new Page<KltStock>(1,10000);
            Page<KltStock> KltStockList = kltStockService.page(KltStockPage, new QueryWrapper<>(kltStock));

            if(KltStockList.getRecords().isEmpty()){
                kltStock.setStockQuantity(KltSalesDetailStockDTO.getStockQuantity());
                kltStock.setStockId(kltStockService.getMaxId()+1);
                kltStock.setCreateSource(operName);
                kltStock.setUpdateUser(operName);
                try {
                    boolean save = kltStockService.save(kltStock);
                } catch (Exception e) {
                    throw new RuntimeException("添加仓库失败");
                }
            }else{
                kltStock.setStockId(KltStockList.getRecords().get(0).getStockId());
                KltStockList.getRecords().get(0).setStockQuantity(KltStockList.getRecords().get(0).getStockQuantity()-KltSalesDetailStockDTO.getSalesQuantity());
                kltStock.setUpdateUser(operName);
                try {
                    boolean save =kltStockService.updateById(KltStockList.getRecords().get(0));
                } catch (Exception e) {
                    throw new RuntimeException("添加仓库失败");
                }
            }
            kltSalesDetail.setSalesOrderId(String.valueOf(kltSalesOrder.getSalesOrderId()));
            kltSalesDetail.setStockId(String.valueOf(kltStock.getStockId()));
            kltSalesDetail.setUnit (KltSalesDetailStockDTO.getUnit());
            kltSalesDetail.setSalesUnitPrice  (KltSalesDetailStockDTO.getSalesUnitPrice());
            kltSalesDetail.setSalesQuantity(KltSalesDetailStockDTO.getSalesQuantity());
            kltSalesDetail.setSalesAmount(KltSalesDetailStockDTO.getSalesAmount());
            kltSalesDetail.setProfit (KltSalesDetailStockDTO.getProfit ());
            kltSalesDetail.setStorageLocation(KltSalesDetailStockDTO.getStorageLocation());
            kltSalesDetail.setArrivalStatus(KltSalesDetailStockDTO.getArrivalStatus());
            kltSalesDetail.setDeliveryStatus(KltSalesDetailStockDTO.getDeliveryStatus());
            kltSalesDetail.setSalesman(KltSalesDetailStockDTO.getSalesman());
            kltSalesDetail.setInvoiceProductCode(KltSalesDetailStockDTO.getInvoiceProductCode());
            kltSalesDetail.setEstimatedArrivalDate (KltSalesDetailStockDTO.getEstimatedArrivalDate());

            kltSalesDetailStockDTOS.add(kltSalesDetail);
        }


        boolean b = kltSalesDetailService.saveBatch(kltSalesDetailStockDTOS);
        String message="";
        if(b){
            message = "导入成功";
        }
        return success(message);
    }
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<KltSalesDetailStockDTO> util = new ExcelUtil<KltSalesDetailStockDTO>(KltSalesDetailStockDTO.class);
        util.importTemplateExcel(response, "销售与库存情况");
    }
    @PostMapping("/export")
    public void export(HttpServletResponse response,  KltSalesDetail kltSalesDetail)
    {
        List<KltSalesDetail> list = kltSalesDetailService.getBaseMapper().selectList(new QueryWrapper<>(kltSalesDetail));
        List<KltSalesDetailStockDTO> list1 = new ArrayList<>();
        list.forEach(kltSalesDetail1->{
            KltSalesDetailStockDTO kltSalesDetailStockDTO = new KltSalesDetailStockDTO();

            if(kltSalesDetail1.getSalesOrderId()!=null&& !kltSalesDetail1.getSalesOrderId().equals("0")){
                KltSalesOrder byId = kltSalesOrderService.getById(kltSalesDetail1.getSalesOrderId());
                kltSalesDetailStockDTO.setSalesOrderNumber(byId.getSalesOrderNumber());
                kltSalesDetailStockDTO.setSalesDeliveryDate(byId.getSalesDeliveryDate());
                kltSalesDetailStockDTO.setSalesDate(byId.getSalesDate());
                kltSalesDetailStockDTO.setCustomerName(byId.getCustomerName());
                kltSalesDetailStockDTO.setSalesInvoiceNumber(byId.getSalesInvoiceNumber());
                kltSalesDetailStockDTO.setSalesInvoiceDate(byId.getSalesInvoiceDate());
                kltSalesDetailStockDTO.setSalesInvoiceQuantity(byId.getSalesInvoiceQuantity());
                kltSalesDetailStockDTO.setSalesInvoiceAmount(byId.getSalesInvoiceAmount());
                kltSalesDetailStockDTO.setUnpaidSalesInvoiceAmount(byId.getUnpaidSalesInvoiceAmount());
                kltSalesDetailStockDTO.setSalesCost(byId.getSalesCost());
                kltSalesDetailStockDTO.setRemarks(byId.getRemarks());
            }
            if(kltSalesDetail1.getStockId()!=null&& !kltSalesDetail1.getSalesOrderId().equals("0")){
                KltStock byId1 = kltStockService.getById(kltSalesDetail1.getStockId());
                kltSalesDetailStockDTO.setProductName(byId1.getProductName());
                kltSalesDetailStockDTO.setModel(byId1.getModel());
                kltSalesDetailStockDTO.setStockQuantity(byId1.getStockQuantity());
                kltSalesDetailStockDTO.setUnit (byId1.getUnit());
            }
            kltSalesDetailStockDTO.setSalesUnitPrice  (kltSalesDetail1.getSalesUnitPrice());
            kltSalesDetailStockDTO.setSalesQuantity (kltSalesDetail1.getSalesQuantity());
            kltSalesDetailStockDTO.setSalesAmount(kltSalesDetail1.getSalesAmount());
            kltSalesDetailStockDTO.setProfit(kltSalesDetail1.getProfit());
            kltSalesDetailStockDTO.setStorageLocation(kltSalesDetail1.getStorageLocation());
            kltSalesDetailStockDTO.setUnit(kltSalesDetail1.getUnit());
            kltSalesDetailStockDTO.setArrivalStatus(kltSalesDetail1.getArrivalStatus());
            kltSalesDetailStockDTO.setDeliveryStatus(kltSalesDetail1.getDeliveryStatus());
            kltSalesDetailStockDTO.setSalesman(kltSalesDetail1.getSalesman());
            kltSalesDetailStockDTO.setInvoiceProductCode (kltSalesDetail1.getInvoiceProductCode());
            kltSalesDetailStockDTO.setEstimatedArrivalDate(kltSalesDetail1.getEstimatedArrivalDate());
            list1.add(kltSalesDetailStockDTO);
        });
        ExcelUtil<KltSalesDetailStockDTO> util = new ExcelUtil<KltSalesDetailStockDTO>(KltSalesDetailStockDTO.class);
        util.exportExcel(response,list1,"销售与库存情况");
    }
}

